<template>
  <el-dialog
    v-model="dialogVisible"
    title="上传封面图片"
    width="500px"
    :before-close="handleClose"
  >
    <el-upload
      class="avatar-uploader"
      action="/api/upload/image" <!-- 替换为实际的图片上传接口 -->
      :show-file-list="false"
      :on-success="handleUploadSuccess"
      :before-upload="beforeUpload"
      :on-error="handleUploadError"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitUpload">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

const emit = defineEmits(['upload-success']);

const dialogVisible = ref(false);
const imageUrl = ref('');

const open = (currentImageUrl = '') => {
  dialogVisible.value = true;
  imageUrl.value = currentImageUrl; // 如果有当前图片，显示出来
};

const handleClose = () => {
  dialogVisible.value = false;
  imageUrl.value = ''; // 关闭时清空图片
};

const handleUploadSuccess = (response, uploadFile) => {
  if (response.code === 200) { // 假设后端返回的成功码是200
    imageUrl.value = response.data.url; // 假设后端返回的图片URL在response.data.url
    ElMessage.success('图片上传成功！');
  } else {
    ElMessage.error('图片上传失败：' + response.message);
  }
};

const handleUploadError = (error) => {
  ElMessage.error('图片上传失败，请重试！');
  console.error('Upload Error:', error);
};

const beforeUpload = (rawFile) => {
  const isJPGorPNG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png';
  const isLt2M = rawFile.size / 1024 / 1024 < 2;

  if (!isJPGorPNG) {
    ElMessage.error('上传封面图片只能是 JPG/PNG 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('上传封面图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

const submitUpload = () => {
  if (imageUrl.value) {
    emit('upload-success', imageUrl.value);
    handleClose();
  } else {
    ElMessage.warning('请先上传图片！');
  }
};

defineExpose({
  open,
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>